/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.legendshop.oa.constants.FunctionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.legendshop.dao.support.PageSupport;
import com.legendshop.framework.controller.BaseController;
import com.legendshop.oa.constants.PathResolver;
import com.legendshop.oa.exception.BusinessException;
import com.legendshop.oa.model.Project;
import com.legendshop.oa.model.ProjectMember;
import com.legendshop.oa.pages.AdminTilesPage;
import com.legendshop.oa.pages.BackPage;
import com.legendshop.oa.pages.RedirectPage;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.security.UserManager;
import com.legendshop.oa.service.ProjectMemberService;
import com.legendshop.oa.service.ProjectService;
import com.legendshop.oa.util.PageSupportHelper;
import com.legendshop.util.AppUtils;

/**
 * The Class ProjectMemberController 控制器
 */
@Controller
@RequestMapping("/admin/projectMember")
public class ProjectMemberController extends BaseController {

	@Autowired
	private ProjectMemberService projectMemberService;

	@Autowired
	private ProjectService projectService;

	/**
	 * 列表查询
	 */
	@RequestMapping("/query/{projectId}")
	public String query(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectId, String curPageNO, String memberName) {
		if (AppUtils.isBlank(projectId)) {
			throw new BusinessException("Project id can not be null while loading project members");
		}
		UserDetail userDetail = UserManager.getUser(request);
		Project project = projectService.getProject(userDetail, projectId);
		request.setAttribute("project", project);
		PageSupport<ProjectMember> ps = projectMemberService.getProjectMemberByProject(projectId, memberName, curPageNO);
		PageSupportHelper.savePage(request, ps);

		request.setAttribute("memberName", memberName);
		return PathResolver.getPath(request, response, AdminTilesPage.PROJECT_MEMBER_LIST_PAGE);
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public String save(HttpServletRequest request, HttpServletResponse response, ProjectMember projectMember) {

		if (AppUtils.isBlank(projectMember.getProjectId())) {
			throw new BusinessException("project id can not be null");
		}

		if (AppUtils.isBlank(projectMember.getUserName())) {
			throw new BusinessException("User name can not be null");
		}

		UserDetail ud = UserManager.getUser(request);
		//检查是否在项目里
		boolean isInProject = projectMemberService.isMemberInProject(ud.getUsername(),projectMember.getProjectId());
		if(!ud.hasFunction(FunctionEnum.FUNCTION_VIEW_ALL_DATA) && !isInProject){
			//不在項目里不能填写工时
			return "noIn";// 失败
		}

		projectMember.setAddTime(new Date());
		projectMemberService.saveProjectMember(projectMember);
		return "success";
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/saveBatch")
	@ResponseBody
	public String saveBatch(HttpServletRequest request, Long projectId, String[] userName, Long[] roleId) {

		if (AppUtils.isBlank(projectId)) {
			throw new BusinessException("project id can not be null");
		}


		UserDetail ud = UserManager.getUser(request);
		//检查是否在项目里
		boolean isInProject = projectMemberService.isMemberInProject(ud.getUsername(), projectId);
		if(!ud.hasFunction(FunctionEnum.FUNCTION_VIEW_ALL_DATA) && !isInProject){
			//不在項目里不能填写工时
			return "noIn";// 失败
		}


		if(userName != null ){
			List<ProjectMember> list = new ArrayList<>();
			Set<String> userNameSet = new HashSet<>();
			Date date = new Date();
			for (int i = 0; i < userName.length; i++) {
				String name = userName[i];
				if(userNameSet.add(name)){
					ProjectMember projectMember = new ProjectMember();
					projectMember.setProjectId(projectId);
					projectMember.setAddTime(date);
					projectMember.setRoleId(roleId[i]);
					projectMember.setUserName(name);
					list.add(projectMember);
				}

			}

			projectMemberService.saveProjectMember(projectId, list);
		}




		return "success";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete/{id}")
	public String delete(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
		ProjectMember projectMember = projectMemberService.getProjectMember(id);

		if (projectMember != null) {
			UserDetail ud = UserManager.getUser(request);
			//检查是否在项目里
			boolean isInProject = projectMemberService.isMemberInProject(ud.getUsername(), projectMember.getProjectId());
			if(!ud.hasFunction(FunctionEnum.FUNCTION_VIEW_ALL_DATA) && !isInProject){
				//不在項目里不能填写工时
				String actionUrl = RedirectPage.PROJECT_MEMBER_LIST_QUERY.getNativeValue() + "/" + projectMember.getProjectId();
				return PathResolver.getPath(request, response, actionUrl, RedirectPage.VARIABLE);
			}

			projectMemberService.deleteProjectMember(projectMember);
			saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("entity.deleted"));
			String actionUrl = RedirectPage.PROJECT_MEMBER_LIST_QUERY.getNativeValue() + "/" + projectMember.getProjectId();
			return PathResolver.getPath(request, response, actionUrl, RedirectPage.VARIABLE);
		}
		return null;
	}

	/**
	 * 根据Id加载
	 */
	@RequestMapping(value = "/loadByProject/{projectId}")
	public String loadByProject(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectId) {	
		request.setAttribute("projectId", projectId);
		return PathResolver.getPath(request, response, BackPage.PROJECT_MEMBER_ADD_PAGE);
	}

	/**
	 * 根据Id批量加载团队
	 */
	@RequestMapping(value = "/loadBatchByProject/{projectId}")
	public String loadBatchByProject(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectId) {
		request.setAttribute("projectId", projectId);

		List<ProjectMember> projectMembers = projectMemberService.getProjectBatchMemberByProject(projectId);

		request.setAttribute("projectMembers", projectMembers);
		Integer count = projectMembers == null ? 0 : projectMembers.size();

		request.setAttribute("count", count);

		return PathResolver.getPath(request, response, BackPage.PROJECT_MEMBER_BATCH_EDIT_PAGE);
	}


	/**
	 * 加载编辑页面
	 */
	@RequestMapping(value = "/load/{projectMemberId}")
	public String load(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectMemberId) {
		ProjectMember projectMember = projectMemberService.getProjectMember(projectMemberId);
        request.setAttribute("projectMember", projectMember);
        request.setAttribute("projectId", projectMember.getProjectId());
        return PathResolver.getPath(request, response, BackPage.PROJECT_MEMBER_ADD_PAGE);
	}

	/**
	 * 加载编辑页面
	 */
	@RequestMapping(value = "/loadEdit/{projectMemberId}")
	public String loadEdit(HttpServletRequest request, HttpServletResponse response, @PathVariable Long projectMemberId) {
		ProjectMember projectMember = projectMemberService.getProjectMember(projectMemberId);
		request.setAttribute("projectMember", projectMember);
		request.setAttribute("projectId", projectMember.getProjectId());
		return PathResolver.getPath(request, response, BackPage.PROJECT_MEMBER_EDIT_PAGE);
	}
	

}
